/**
 * 捕获整数前缀
 * @param {string} input
 * @returns {string}
 */
const matchInteger = input => {
  const match = input.match(/^[-+]?\d*/)
  if (!match) return ''

  const res = match[0]
  if (res === '+' || res === '-' || res === '') return res
  return String(+res)
}

/**
 * 捕获数值前缀
 * @param {string} input
 * @returns {string}
 */
const matchNumber = input => {
  const match = input.match(/^[-+]?\d*\.?\d*/)
  if (!match) return ''

  const res = match[0]
  if (res === '+' || res === '-' || res === '') return res
  // 直接去掉前缀 0
  let sign = res[0] === '-' ? '-' : ''
  if (/^[-+]?0+$/.test(res)) return `${sign}0`

  return res
}

/**
 * 验证并返回整数字符串
 * @param {string} input
 * @returns {string}
 */
const validateInteger = function(input) {
  const { min, max } = this
  let match = matchInteger(input) // 此处一定是一个合法的数值
  if (+match > max) return String(max)
  if (+match < min) return String(min)

  return match
}

/**
 * 验证并返回数值字符串
 * @param {string} input
 * @returns {string}
 */
const validateNumber = function(input) {
  const { min, max } = this
  const match = matchNumber(input) // 此处一定是一个合法的数值
  if (match === '') return match
  if (match === '.' || match === '+.') return '0.'
  if (match === '-.') return '-0.'
  if (+match > max) return String(max)
  if (+match < min) return String(min)

  return match
}

/**
 * 失去焦点时格式化并返回数字字符串
 * @param {string} input
 * @returns {string}
 */
const handleBlur = function(input) {
  const N = input.length
  if (N === 0) return ''
  if (input === '+' || input === '-') return ''
  if (input[N - 1] === '.') return input.substring(0, N - 1)

  return input
}

export default function useInputValidate({
  min = Number.MIN_SAFE_INTEGER,
  max = Number.MAX_SAFE_INTEGER,
  type = 'number', // number | integer
}) {

  const res = { handleBlur }
  if (type === 'integer') {
    res.handleValidate = validateInteger.bind({ min, max })
  } else {
    res.handleValidate = validateNumber.bind({ min, max })
  }

  return res
}